<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>多图上传压缩</title>
    <link rel="stylesheet" type="text/css" href="../css/api.css" />
</head>
<style>
    [v-cloak] {
        display: none;
    }

    section {
        margin: 0;
        padding: 0;
        overflow: hidden;
    }

    header {
        padding: 10px
    }

    .topleft {
        font-size: 16px;
        color: #333;
        line-height: 180%;
        padding: 10px;
    }

    .item {
        float: left;
        width: 27%;
        padding: 3%;
    }

    .addimg {
        position: relative;
    }

    .hiddenimg {
        position: relative;
        width: 100%;
        height: 100%;
        overflow: hidden;
        margin: 0;
        padding-bottom: 100%;
        background-position: center center;
        background-repeat: no-repeat;
        background-size: cover;
        border-radius: 5px;
    }

    .delete {
        position: absolute;
        z-index: 999;
        right: -5px;
        margin-top: -15px;
        width: 30px;
        height: 30px;
        background: url(../image/icon_delete.png);
        background-position: center center;
        background-size: 30px 30px;
        background-repeat: no-repeat;
    }

    .item img {
        width: 100%;
        border-radius: 5px;
    }
</style>

<body>
    <section id="listimg" v-cloak>
        <div class="topleft">
            添加更多图片(最多只能添加9张):
        </div>
        <div class="right">
            <div class="item addimg" v-for="(list,index) in listimg">
                <div class="delete" @click="fnDeleteImg(index);"></div>
                <div class="hiddenimg" :style="fnBgImg(list.path)"></div>
            </div>
            <div class="item add" @click="fnOpenUIAlbumBrowser();" v-if="listimg.length<9">
                <img src="../image/icon_add.png">
            </div>
        </div>
    </section>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/vue.min.js"></script>
<!-- 消除移动端点击延迟300ms -->
<script type="text/javascript" src="../script/fastclick.js"></script>
<script>
    apiready = function() {
        //  初始化Vuw
        fnInVue();
    }

    function fnInVue() {
        window.ListVue = new Vue({
            el: "#listimg",
            data: {
                listimg: [],
                number: 0
            },
            mounted: function() {
                this.$nextTick(function() {
                    fnInit();
                });
            },
            methods: {
                fnBgImg: function(img) {
                    var bg = 'background-image: url(' + img + ');'
                    return bg;
                },
                // 删除图片
                fnDeleteImg: function(index) {
                    this.listimg.splice(index, 1);
                    this.number = this.number - 1;
                },
                // 打开多图模块
                fnOpenUIAlbumBrowser: function() {
                    var number;
                    // 为空最多上传6个
                    if (this.number == 0) {
                        number = 9;
                    }
                    if (this.number > 0 && this.number < 9) { // 大于0少于六6减去实际的图片数
                        number = 9 - this.number;
                    }
                    if (this.number == 9) {
                        console.log(this.number);
                        api.toast({
                            msg: '不能再添加啦',
                            duration: 3000,
                            location: 'bottom'
                        });
                        return;
                    }
                    UIAlbumBrowser.open({
                        type: 'image',
                        max: number, //这里根据上面的判断最多可以选择多少张
                        isOpenPreview: true,
                        styles: {
                            bg: '#fff',
                            mark: {
                                unSelectedIcon: 'widget://image/icon/icon_group.png',
                                icon: 'widget://image/icon/icon_group_on.png',
                                position: 'top_right',
                                size: 18
                            },
                            nav: {
                                bg: '#9EC509',
                                stateColor: '#9EC509',
                                stateSize: 16,
                                cancleBg: 'rgba(0,0,0,0)',
                                cancelColor: '#fff',
                                cancelSize: 16,
                                finishBg: '#9EC509',
                                finishColor: '#fff',
                                unFinishColor: "#fff",
                                numberTextColor: '#9EC509',
                                numberBgColor: '#fff',
                                finishSize: 16
                            },
                            bottomTabBar: {
                                bg: '#9EC509',
                                unPreviewTitleColor: '#9EC5095',
                                previewTitleColor: '#fff',
                                previewTitleSize: 15,
                            }
                        }
                    }, function(ret) {
                        // 判断是点击确定按钮 在执行图片压缩发送图片到服务器
                        if (ret.eventType == 'confirm' && ret.list.length > 0) {
                            // 因为打开模块会出现app关闭console.log无法打印所以延迟一下
                            setTimeout(function() {
                                var imgPaths = [];
                                if (api.systemType == "ios") { //ios图片还需要经过模糊图片查找到未压缩的图片
                                    var imgPathsdata = [];
                                    for (var i = 0; i < ret.list.length; i++) {
                                        var data = {
                                            "path": ret.list[i].path
                                        };
                                        imgPathsdata.push(data);
                                    }
                                    fnUIAlbumBrowsertransPath(imgPathsdata, function(cb) {
                                        for (var i = 0; i < cb.length; i++) {
                                            var data = {
                                                "path": cb[i]
                                            };
                                            imgPaths.push(data);
                                        }
                                        // 得到真实图片路径在进行图片压缩
                                        fnimageFilter_callback(imgPaths, function(cb) {
                                            setTimeout(function() {
                                                // 得到回调后的压缩图片
                                                var imgpaths = [];
                                                for (var i = 0; i < cb.length; i++) {
                                                    var data = {
                                                        "path": cb[i]
                                                    }
                                                    imgpaths.push(data);
                                                }
                                                fnshow_img(imgpaths);
                                            }, 300)
                                        });
                                    });
                                } else { //安卓可以直接使用图片
                                    for (var i = 0; i < ret.list.length; i++) {
                                        var data = {
                                            "path": ret.list[i].path
                                        };
                                        imgPaths.push(data);
                                    }
                                    // 发送数据
                                    fnimageFilter_callback(imgPaths, function(cb) {
                                        setTimeout(function() {
                                            // 得到回调后的压缩图片数组发送到服务器
                                            var imgpaths = [];
                                            for (var i = 0; i < cb.length; i++) {
                                                var data = {
                                                    "path": cb[i]
                                                }
                                                imgpaths.push(data);
                                            }
                                            fnshow_img(imgpaths);
                                        }, 300)
                                    });
                                }
                            }, 300)
                        }
                    });
                }
            }
        });
    }

    var UIAlbumBrowser, imageFilter;

    function fnInit() {
        // 引用多图上传模块
        UIAlbumBrowser = api.require('UIAlbumBrowser');
        // 引用压缩图片模块
        imageFilter = api.require('imageFilter');
    }

    //  获取ios 未缩的图片
    function fnUIAlbumBrowsertransPath(imgPath, callback) {
        var arr = [];
        for (var i = 0; i < imgPath.length; i++) {
            (function(index) {
                UIAlbumBrowser.transPath({
                    path: imgPath[index].path
                }, function(ret, err) {
                    if (ret) {
                        arr.push(ret.path);
                        if (arr.length === imgPath.length) {
                            // 回调压缩后面图片数组
                            callback(arr);
                        }
                    } else {
                        toast(err.msg);
                    }
                });
            })(i);
        }
    }

    // 循环里面不能用异步函数，所以使用闭包跟回调函数 最后一个图片压缩完之后才发送
    function fnimageFilter_callback(imgPath, callback) {
        var arr = [];
        for (var i = 0; i < imgPath.length; i++) {
            (function(index) {
                // 压缩图片后的本地地址
                var eImgPath = api.fsDir + '/cache/';
                //获取图片后辍
                var pos = imgPath[index].path.lastIndexOf('.');
                var etype = imgPath[index].path.substr(pos + 1);
                //图片文件名
                var imgName = 'imgcachefeedback' + (Date.parse(new Date()) / 1000) + (Math.round(Math.random() * 100000)) + '.' + etype + '';
                // 打开图片压缩
                imageFilter.compress({
                    img: imgPath[i].path,
                    quality: 0.6,
                    save: {
                        imgPath: 'fs://cache',
                        imgName: imgName
                    }
                }, function(ret, err) {
                    if (ret) {
                        if (ret.status == 1) {
                            arr.push(eImgPath + imgName);
                            if (arr.length == imgPath.length) {
                                // 回调压缩后面图片数组
                                callback(arr);
                            }
                        } else {
                            toast("压缩图片失败，请稍后再试", 3000);
                        }
                    } else {
                        toast(err.msg, 3000);
                    }
                });
            })(i);
        }
    }

    function fnshow_img(imgpaths) {
        // 数据追加
        var listimg = window.ListVue.listimg.concat(imgpaths);
        setTimeout(function() {
            window.ListVue.listimg = listimg;
            window.ListVue.number = window.ListVue.listimg.length;
        }, 300)
    }
</script>

</html>
